package com.wlyuan.open.infrastructure.repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlyuan.open.dao.entity.PushTaskDO;
import com.wlyuan.open.dao.mapper.PushTaskMapper;
import com.wlyuan.open.domain.PushTask;
import com.wlyuan.open.domain.PushTaskId;
import com.wlyuan.open.domain.PushTaskStatus;
import com.wlyuan.open.domain.repository.PushTaskRepository;
import com.wlyuan.open.infrastructure.converter.PushTaskConverter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class PushTaskRepositoryImpl implements PushTaskRepository {

    private final PushTaskMapper pushTaskMapper;

    @Override
    public PushTask ofId(PushTaskId pushTaskId) {
        return null;
    }

    @Override
    public PushTaskId save(PushTask object) {
        var pushTaskDO = PushTaskConverter.convert(object);
        if(object.getId() == null){
            pushTaskMapper.insert(pushTaskDO);
        }else {
            pushTaskMapper.updateById(pushTaskDO);
        }
        object.setId(new PushTaskId(pushTaskDO.getId()));
        return object.getId();
    }

    @Override
    public List<PushTaskId> save(List<PushTask> tasks){
        //todo 批量
        List<PushTaskId> taskIds = new ArrayList<>(tasks.size());
        for(PushTask pushTask:tasks){
            taskIds.add(save(pushTask));
        }
        return taskIds;
    }

    @Override
    public void remove(PushTaskId pushTaskId) {

    }

    @Override
    public List<PushTask> listNeedPush(Long page, Long size) {
        QueryWrapper<PushTaskDO> query = new QueryWrapper<>();
        query.lambda().eq(PushTaskDO::getStatus, PushTaskStatus.CREATED.getValue());
        var result = pushTaskMapper.selectPage(new Page<>(page, size), query);
        if (CollectionUtils.isEmpty(result.getRecords())) {
            return Collections.emptyList();
        }
        return result.getRecords().stream().map(PushTaskConverter::convert).collect(Collectors.toList());
    }

    @Override
    public List<PushTask> listByIds(List<Long> taskIds) {
        QueryWrapper<PushTaskDO> query = new QueryWrapper<>();
        query.lambda().in(PushTaskDO::getId,taskIds);
        var result = pushTaskMapper.selectList(query);
        if (CollectionUtils.isEmpty(result)) {
            return Collections.emptyList();
        }
        return result.stream().map(PushTaskConverter::convert).collect(Collectors.toList());

    }
}
